package publisher

import (
	"encoding/json"
	"github.com/streadway/amqp"
	cfg "github.com/ufoscout/go-up"
	"go.uber.org/zap"
	"longmen/server/pkg/common/lib/rabbitmq"
)

const (
	UsageStatistic    StatType = iota + 1 // 使用计数
	LoginStatistic                        // 通过getUserinfo的登录计数
	RegisterStatistic                     // 注册计数
	LoginApiStatistic                     // 通过login的登录计数
)

const (
	// WEB 注册来源  web-0; ios-1; android-2 3-H5
	WEB = iota
	IOS
	Android
	H5
)

// MobileDeviceGroup 移动设备
var MobileDeviceGroup = []int{
	IOS, Android,
}

type (
	StatType     int
	PublishStats struct {
		StatType   StatType `json:"stat_type"`   // 统计类型
		UserId     int      `json:"user_id"`     // 统计的用户
		DeviceUUID string   `json:"device_uuid"` // 设备ID
		ClientIp   string   `json:"client_ip"`   // 客户端IP
		PlatForm   int8     `json:"plat_form"`   // 平台
	}
	PublishStatisticServices struct {
		instance *rabbitmq.Producer // 发送实例
	}
)

// NewPublish 开启一个生产实例
func NewStatisticPublish(conf cfg.GoUp, rabbitConf rabbitmq.Config, publishName string, logger *zap.SugaredLogger) (*PublishStatisticServices, error) {
	mq := rabbitmq.New(&rabbitConf, logger)
	c, queue, options := rabbitmq.GetRabbitProducerConfig(conf, publishName)
	producer, err := mq.NewProducer(c, queue, options)
	if err != nil {
		logger.Errorf("new producer err: %v", err)
		return nil, err
	}

	return &PublishStatisticServices{
		instance: producer,
	}, nil
}

// StatisticPush 发送一个统计类的数据
func (p *PublishStatisticServices) StatisticPush(statType StatType, userId int, uuid, ip string, plat int8) error {
	body, _ := json.Marshal(PublishStats{
		StatType:   statType,
		UserId:     userId,
		DeviceUUID: uuid,
		ClientIp:   ip,
		PlatForm:   plat,
	})
	return p.instance.Publish(amqp.Publishing{
		DeliveryMode: amqp.Persistent,
		ContentType:  "application/json",
		Body:         body,
	})
}
